/**
 * @author 蔡明宗
 * @date 2010-11-25 下午10:06:20
 */

package com.ad.components;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Id;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Cookies;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.util.TextStreamResponse;

import com.ad.models.NaviItem;
import com.ad.services.IUserManagerService;
import com.ad.system.Common;
import com.ad.system.State;
import com.ad.system.SystemVariable;

/**
 * 组件，代表页面上部
 * 
 * @author 蔡明宗
 * 
 */
public class Top {

	@Property
	@SessionState
	private State state;

	@Inject
	private Cookies cookies;

	@Inject
	private Request request;

	@Property
	private String email;

	@Property
	private String password;

	@Property
	@Persist
	private String nickName;

	@Property
	private String page;

	/**
	 * 面包屑导航列表
	 */
	@SuppressWarnings("unused")
	@Property
	@Parameter
	private List<NaviItem> naviList;

	@Property
	private NaviItem item;

	@Inject
	private ComponentResources componentResources;

	@Inject
	@Id("userService")
	private IUserManagerService userService;

	protected void setupRender() {
		page = componentResources.getPageName();

		// 从cookie中读取email信息
		String email = "";
		try {
			String emailFormCookie = cookies
					.readCookieValue(SystemVariable.COOKIES_USER_EMAIL);
			if (!Common.isEmpty(emailFormCookie)) {
				email = URLDecoder.decode(emailFormCookie, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 如果email不为空，则存入session
		if (!Common.isEmpty(email)) {
			state.setEmail(email);
		}

		if (Common.isEmpty(this.nickName)) {
			// 如果昵称为空，先从cookie中读取
			try {
				String nickNameFormCookies = cookies
						.readCookieValue(SystemVariable.COOKIES_USER_NAME);
				if (!Common.isEmpty(nickNameFormCookies)) {
					nickName = URLDecoder.decode(nickNameFormCookies, "UTF-8");
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// 如果cookie中读取仍为空，通过email查询获得
			if (Common.isEmpty(this.nickName) && !Common.isEmpty(email)) {
				nickName = this.userService
						.getUserNameByEmail(state.getEmail());
			}
		}
	}

	/**
	 * 是否显示面包屑导航（首页》》搜索），如果是主页，不显示
	 * 
	 * @return
	 */
	public boolean isShow() {
		return !page.equals("Home");
	}

	/**
	 * 是否是自身页面
	 * 
	 * @return
	 */
	public boolean isSelf() {
		return item.getUrl().equalsIgnoreCase(page);
	}

	// Object onSuccessFromlogForm() {
	// nickName = this.userService.check(this.email, password);
	// if (!nickName.equalsIgnoreCase("")) {
	// state.setEmail(email);
	// // 需要对中文进行编码
	// try {
	// cookies.writeCookieValue(SystemVariable.COOKIES_USER_NAME,
	// URLEncoder.encode(nickName, "UTF-8"),
	// SystemVariable.WEEK);
	// cookies.writeCookieValue(SystemVariable.COOKIES_USER_EMAIL,
	// URLEncoder.encode(email, "UTF-8"), SystemVariable.WEEK);
	// } catch (UnsupportedEncodingException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }
	//
	// String result =
	// "<script type='text/javascript'>alert('用户名或密码错误');window.history.back();</script>";
	// return new TextStreamResponse("text/html", result);
	// }

	Object onActionFromLogin() {
		email = request.getParameter("email");
		password = request.getParameter("password");
		nickName = this.userService.check(email, password);
		String result = "";
		if (!nickName.equalsIgnoreCase("")) {
			result = "login";
			state.setEmail(email);
			// 需要对中文进行编码
			try {
				cookies.writeCookieValue(SystemVariable.COOKIES_USER_NAME,
						URLEncoder.encode(nickName, "UTF-8"),
						SystemVariable.WEEK);
				cookies.writeCookieValue(SystemVariable.COOKIES_USER_EMAIL,
						URLEncoder.encode(email, "UTF-8"), SystemVariable.WEEK);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			result = "loginFalse";
		}

		return new TextStreamResponse("text/html", String.format("%s", result));
	}

	Object onActionFromLogout() {
		state.setEmail(null);
		this.nickName = "";
		this.cookies.removeCookieValue(SystemVariable.COOKIES_USER_EMAIL);
		this.cookies.removeCookieValue(SystemVariable.COOKIES_USER_NAME);
		return new TextStreamResponse("text/html", "logout");
	}

}
